package com.kkkk.rest.common.exception.code.annotation;



import com.kkkk.rest.common.model.ErrorMessage;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author wangy
 * @Date 2021/10/19 9:59
 */
public class AnnotationErrorCodeWrapper {

    private static Map<AnnotationErrorCode, ErrorMessage> map = new ConcurrentHashMap<>();


    public static ErrorMessage get(AnnotationErrorCode errorCode) {
        ErrorMessage errorMessage = map.get(errorCode);
        if (errorMessage != null) {
            return errorMessage;
        }

        synchronized (AnnotationErrorCodeWrapper.class) {
            errorMessage = map.get(errorCode);
            if (errorMessage != null) {
                return errorMessage;
            }
            try {
                Enum<?> codeEnum = (Enum<?>) errorCode;

                // 错误码 内部业务模块
                ErrorCodeModule codeModule = errorCode.getClass().getAnnotation(ErrorCodeModule.class);

                // 错误码详情
                ErrorCodeMessage c = errorCode.getClass().getField(codeEnum.name()).getAnnotation(ErrorCodeMessage.class);

                String code = c.type().getCode() + codeModule.value() + c.code();

                errorMessage = new ErrorMessage();

                errorMessage.setMsg(c.message());

                errorMessage.setCode(code);

                map.put(errorCode, errorMessage);

                return errorMessage;
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
                return null;
            }
        }
    }
}
